package com.winning.util.excelutil.util;

import com.winning.util.excelutil.common.exception.BaseException;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @作者： caopengfei
 * @时间： 2020/2/13
 */
@Slf4j
public class FileUtil {

    public static HttpServletResponse downLoadFiles(List<File> files,
       HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {

            File file = new File("数据导入模板.rar");
            if (!file.exists()){
                file.createNewFile();
            }
            response.reset();
            //response.getWriter()
            //创建文件输出流
            FileOutputStream fous = new FileOutputStream(file);

            ZipOutputStream zipOut = new ZipOutputStream(fous);
            zipFile(files, zipOut);
            zipOut.close();
            fous.close();
            return downloadZip(file,response);
        }catch (Exception e) {
           log.error("下载失败",e);
        }
        return response ;
    }

    /**
     * 把接受的全部文件打成压缩包
     */
    public static void zipFile (List files,ZipOutputStream outputStream) {
        int size = files.size();
        for(int i = 0; i < size; i++) {
            File file = (File) files.get(i);
            zipFile(file, outputStream);
        }
    }

    public static HttpServletResponse downloadZip(File file,HttpServletResponse response) {
        try {
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            String fileName  = new String(file.getName().getBytes(), "ISO-8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="+fileName);
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {

        }finally{
            try {
                File f = new File(file.getPath());
                f.delete();
            } catch (Exception e) {
                log.error("下载失败",e);
            }
        }
        return response;
    }

    /**
    * @vsts_no：
    * @comment： 文件打包
    * @author： caopengfei
    * @time：  2020/2/13 21:24
    */
    public static void zipFile(File inputFile,ZipOutputStream ouputStream) {
        try {
            if(inputFile.exists()) {
                if (inputFile.isFile()) {
                    FileInputStream IN = new FileInputStream(inputFile);
                    BufferedInputStream bins = new BufferedInputStream(IN, 512);
                    //org.apache.tools.zip.ZipEntry
                    ZipEntry entry = new ZipEntry(inputFile.getName());
                    ouputStream.putNextEntry(entry);
                    // 向压缩文件中输出数据
                    int nNumber;
                    byte[] buffer = new byte[512];
                    while ((nNumber = bins.read(buffer)) != -1) {
                        ouputStream.write(buffer, 0, nNumber);
                    }
                    // 关闭创建的流对象
                    bins.close();
                    IN.close();
                } else {
                    try {
                        File[] files = inputFile.listFiles();
                        for (int i = 0; i < files.length; i++) {
                            zipFile(files[i], ouputStream);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            log.error("压缩文件失败",e);
        }
    }

    public static List<File> readFolder(String filepath) throws FileNotFoundException, IOException {
        List<File> files = new ArrayList<>();
            File file = new File(filepath);
            if (file.isDirectory()) {
                String[] filelist = file.list();
                if(filelist == null || filelist.length==0){
                    return  files;
                }
                for (int i = 0; i < filelist.length; i++) {
                    File readfile = new File(filepath + "\\" + filelist[i]);
                   if(!readfile.isDirectory()){
                       files.add(readfile);
                   }
                }
            }
        return files;
    }

}
